import { book, addbook, deletebook, updatebook } from '@/services/ant-design-pro';
import { PlusOutlined } from '@ant-design/icons';
import {
    ActionType,
    ProColumns,
    ProFormInstance,
} from '@ant-design/pro-components';
import {
    ModalForm,
    PageContainer,
    ProFormTextArea,
    ProTable,
} from '@ant-design/pro-components';
import { FormattedMessage } from '@umijs/max';
import { Button, message, Popconfirm } from 'antd';
import React, { useRef, useState } from 'react';

/**
 * @en-US Add node
 * @zh-CN 添加节点
 * @param fields
 */
const handleAdd = async (fields: API.RuleListItem) => {
    const hide = message.loading('正在添加');
    try {
        await addbook({ ...fields });
        hide();
        message.success('Added successfully');
        return true;
    } catch (error) {
        hide();
        message.error('Adding failed, please try again!');
        return false;
    }
};

/**
 * @en-US Update node
 * @zh-CN 更新节点
 *
 * @param fields
 */
// eslint-disable-next-line @typescript-eslint/no-unused-vars
const handleUpdate = async (fields: any) => {
    const hide = message.loading('Configuring');
    try {
        await updatebook({
            ...fields,
            id: fields.id,
        });
        hide();

        message.success('Configuration is successful');
        return true;
    } catch (error) {
        hide();
        message.error('Configuration failed, please try again!');
        return false;
    }
};

const TableList: React.FC = () => {
    const updateFormRef = useRef<ProFormInstance>();
    /**
     * @en-US Pop-up window of new window
     * @zh-CN 新建窗口的弹窗
     *  */
    const [createModalVisible, handleModalVisible] = useState<boolean>(false);
    /**
     * @en-US The pop-up window of the distribution update window
     * @zh-CN 分布更新窗口的弹窗
     * */
    const [currentRow, setCurrentRow] = useState<any>();
    const [updateModalVisible, handleUpdateModalVisible] = useState<boolean>(false);

    const actionRef = useRef<ActionType>();
    const confirmDeleteFactor = async (record: any) => {
        try {
            const { success } = await deletebook(record);
            if (success) {
                if (actionRef.current) {
                    actionRef.current.reload();
                }
            }
            message.success('Click on Yes');
        } catch (error) {
            message.error('Delete failed, please try again!');
            return false;
        }
    };
    const columns: ProColumns<any>[] = [
        {
            title: '图书id',
            dataIndex: 'bookId',
        },
        {
            title: '条形码',
            dataIndex: 'TXM',
        },
        {
            title: '图书名称',
            dataIndex: 'title',
        },
        {
            title: 'ISBN',
            dataIndex: 'ISBN',
        },
        {
            title: '图书类型',
            dataIndex: 'TSLX',
        },
        {
            title: '作者',
            dataIndex: 'author',
        },
        {
            title: '出版社',
            dataIndex: 'CBS',
        },
        {
            title: '书架名称',
            dataIndex: 'SJMC',
        },
        {
            title: <FormattedMessage id="pages.searchTable.titleOption" defaultMessage="Operating" />,
            key: 'option',
            valueType: 'option',
            render: (_, record) => {
                return [
                    <a key="edit" onClick={() => {
                        handleUpdateModalVisible(true)
                        setCurrentRow(record)
                    }}>
                        编辑
                    </a>,
                    <Popconfirm
                        title="你确定要删除该图书吗?"
                        onConfirm={() => confirmDeleteFactor(record)}
                        okText="Yes"
                        cancelText="No"
                        key={record.id}
                    >
                        <a key="subscribeAlert">删除图书</a>
                    </Popconfirm>,
                ];
            },
        },
    ];

    return (
        <PageContainer>
            <ProTable<any, API.PageParams>
                headerTitle={'图书管理'}
                actionRef={actionRef}
                rowKey="id"
                search={{
                    labelWidth: 120,
                }}
                toolBarRender={() => [
                    <Button
                        type="primary"
                        key="primary"
                        onClick={() => {
                            handleModalVisible(true);
                        }}
                    >
                        <PlusOutlined /> <FormattedMessage id="pages.searchTable.new" defaultMessage="New" />
                    </Button>,
                ]}
                request={book}
                columns={columns}
            />
            <ModalForm
                formRef={updateFormRef}
                labelCol={{ span: 4 }}
                wrapperCol={{ span: 26 }}
                layout={'horizontal'}
                title={'新增图书'}
                width="600px"
                visible={createModalVisible}
                onVisibleChange={(visible) => {
                    handleModalVisible(visible);
                }}
                onFinish={async (value) => {
                    const success = await handleAdd(value as API.RuleListItem);
                    if (success) {
                        handleModalVisible(false);
                        if (actionRef.current) {
                            actionRef.current.reload();
                        }
                    }
                }}
            >
                <ProFormTextArea
                    label={'条形码'}
                    rules={[
                        {
                            required: true,
                            message: '条形码为必选项',
                        },
                    ]}
                    width="md"
                    name="TXM"
                />
                <ProFormTextArea
                    label={'图书名称'}
                    rules={[
                        {
                            required: true,
                            message: '图书名称为必选项',
                        },
                    ]}
                    width="md"
                    name="title"
                />
                <ProFormTextArea
                    label={'ISBN'}
                    rules={[
                        {
                            required: true,
                            message: 'ISBN为必选项',
                        },
                    ]}
                    width="md"
                    name="ISBN"
                />
                <ProFormTextArea
                    label={'作者'}
                    rules={[
                        {
                            required: true,
                            message: '作者为必选项',
                        },
                    ]}
                    width="md"
                    name="author"
                />
                <ProFormTextArea
                    label={'图书类型'}
                    rules={[
                        {
                            required: true,
                            message: '图书类型为必选项',
                        },
                    ]}
                    width="md"
                    name="TSLX"
                />
                 <ProFormTextArea
                    label={'出版社'}
                    rules={[
                        {
                            required: true,
                            message: '出版社为必选项',
                        },
                    ]}
                    width="md"
                    name="CBS"
                />
                <ProFormTextArea
                    label={'书架名称'}
                    rules={[
                        {
                            required: true,
                            message: '书架名称为必选项',
                        },
                    ]}
                    width="md"
                    name="SJMC"
                />
                
            </ModalForm>
            <ModalForm
                labelCol={{ span: 4 }}
                wrapperCol={{ span: 16 }}
                layout={"horizontal"}
                title={"修改图书信息"}
                initialValues={{ ...(currentRow || {}) }}
                width="600px"
                visible={updateModalVisible}
                onVisibleChange={visible => {
                    handleUpdateModalVisible(visible)
                    if (visible) {
                        updateFormRef.current?.setFieldsValue({
                            ...currentRow
                        })
                    } else {
                        setCurrentRow(undefined)
                    }
                }}
                onFinish={async (value) => {
                    const success = await handleUpdate({ ...currentRow, ...value as any, });
                    if (success) {
                        handleUpdateModalVisible(false);
                        if (actionRef.current) {
                            actionRef.current.reload();
                        }
                    }
                }}
            >
                <ProFormTextArea
                    label={'条形码'}
                    rules={[
                        {
                            required: true,
                            message: '条形码为必选项',
                        },
                    ]}
                    width="xl"
                    name="TXM"
                />
                <ProFormTextArea
                    label={'图书名称'}
                    rules={[
                        {
                            required: true,
                            message: '图书名称为必选项',
                        },
                    ]}
                    width="md"
                    name="title"
                />
                <ProFormTextArea
                    label={'ISBN'}
                    rules={[
                        {
                            required: true,
                            message: 'ISBN为必选项',
                        },
                    ]}
                    width="md"
                    name="ISBN"
                />
                                <ProFormTextArea
                    label={'作者'}
                    rules={[
                        {
                            required: true,
                            message: '作者为必选项',
                        },
                    ]}
                    width="md"
                    name="author"
                />
                <ProFormTextArea
                    label={'图书类型'}
                    rules={[
                        {
                            required: true,
                            message: '图书类型为必选项',
                        },
                    ]}
                    width="md"
                    name="TSLX"
                />
                 <ProFormTextArea
                    label={'出版社'}
                    rules={[
                        {
                            required: true,
                            message: '出版社为必选项',
                        },
                    ]}
                    width="md"
                    name="CBS"
                />
                 <ProFormTextArea
                    label={'书架名称'}
                    rules={[
                        {
                            required: true,
                            message: '书架名称为必选项',
                        },
                    ]}
                    width="md"
                    name="SJMC"
                />
            </ModalForm>
        </PageContainer>
    );
};

export default TableList;
